import {MessageBox, Notification} from 'element-ui'

/*
*  操作状态反馈
*  用户确认 -> 请求ajax 成功则提示成功，失败则提示失败
*  @param ajax {Promise}
*
* */
export function status_prompt({ajax, success_text = '操作成功', fail_text = '操作失败'}) {
  return new Promise((resolve, reject) => {
    ajax().then(x => {
      const {code, obj} = x
      const config = {
        type: 'success',
        title: '温馨提示',
        message: success_text
      }
      if (code != undefined) {
        if (code == 200 && obj) {
          Notification(config)
          resolve()
        } else {
          config.type = 'error'
          config.message = fail_text
          Notification(config)
          reject()
        }
      } else {
        Notification({...config, ...x})
        x.resolve ? resolve() : reject('操作失败')
      }
    }).catch(e => {
      if (e.name == 801) {
        fail_text = e.message || fail_text
      }
      Notification.error({
        title: '温馨提示',
        message: fail_text
      })
      reject(e)
    })
  })
}

/*
*  询问操作反馈
*  用户确认 -> 请求ajax 成功则提示成功，失败则提示失败
*  @param ajax {Promise}
*
* */
export async function confirm_handler({ajax, hint = '确认操作', title = '温馨提示', type, success_text = '操作成功', fail_text = '操作失败'}) {
  await MessageBox.confirm(hint, title, {type})
  return status_prompt(...arguments)
}
